#include "youdaotrans.h"
#include <QApplication>
#include <QClipboard>
#include <QMessageBox>
#include <QSettings>

YoudaoTrans::YoudaoTrans(QObject *parent) { Q_UNUSED(parent); }

int YoudaoTrans::sdkVersion() { return SDKVERSION; }

QString YoudaoTrans::signature() { return WINGSUMMER; }

YoudaoTrans::~YoudaoTrans() {}

bool YoudaoTrans::init(QList<WingPluginInfo> loadedplugin) {
  Q_UNUSED(loadedplugin);

  if (!localiztion) // 加载语言本地化失败，报告失败
    return false;

  // 初始化剪切板监控
  auto clipboard = qApp->clipboard();
  connect(clipboard, &QClipboard::selectionChanged, this, [=] {
    if (trans->sel()) {
      lastword = clipboard->text(QClipboard::Selection);
    }
  });
  connect(clipboard, &QClipboard::dataChanged, this, [=] {
    if (trans->cp()) {
      auto word = clipboard->text();
      if (trans->isVaildWord(word))
        trans->translate(word);
    }
  });

  return true;
}

void YoudaoTrans::unload() { trans->saveSettings(); }

QString YoudaoTrans::pluginName() { return tr("YoudaoTrans"); }

QString YoudaoTrans::pluginAuthor() { return WINGSUMMER; }

IWingToolPlg::Catagorys YoudaoTrans::pluginCatagory() {
  return IWingToolPlg::Catagorys::Productivity;
}

uint YoudaoTrans::pluginVersion() { return 1; }

QString YoudaoTrans::pluginComment() {
  return tr("A useful En2Zh translate plugin for WingTool");
}

QString YoudaoTrans::pluginWebsite() {
  return "https://code.gitlink.org.cn/wingsummer/YoudaoTrans";
}

QIcon YoudaoTrans::pluginIcon() { return QIcon(":/youdaotr/icon.png"); }

const QMetaObject *YoudaoTrans::serviceMeta() { return trans->metaObject(); }

const QPointer<QObject> YoudaoTrans::serviceHandler() {
  return QPointer<QObject>(trans);
}

HookIndex YoudaoTrans::getHookSubscribe() { return HookIndex::ButtonRelease; }

bool YoudaoTrans::preInit() {
  trans = new YoudaoService(this);
  return true;
}

QString YoudaoTrans::translatorFile() { return "YoudaoTrans.qm"; }

QVariant YoudaoTrans::pluginServicePipe(int serviceID, QList<QVariant> params) {
  Q_UNUSED(serviceID);
  Q_UNUSED(params);
  return QVariant();
}

void YoudaoTrans::onPluginCenter() { trans->showSettings(); }

void YoudaoTrans::buttonRelease(Qt::MouseButton btn, int x, int y) {
  Q_UNUSED(x);
  Q_UNUSED(y);
  if (trans->enabled() && trans->sel() && btn == Qt::MouseButton::LeftButton) {
    if (trans->isVaildWord(lastword))
      trans->translate(lastword);
  }
  lastword.clear();
}

#if QT_VERSION < 0x050000
Q_EXPORT_PLUGIN2(YoudaoTrans, GenericPlugin)
#endif // QT_VERSION < 0x050000
